package com.scm.web.controller.inventory;

import com.scm.common.annotation.Log;
import com.scm.common.core.controller.BaseController;
import com.scm.common.core.domain.AjaxResult;
import com.scm.common.core.domain.entity.SysUser;
import com.scm.common.core.page.PageDomain;
import com.scm.common.core.page.TableDataInfo;
import com.scm.common.core.page.TableSupport;
import com.scm.common.enums.BusinessType;
import com.scm.common.exception.ServiceException;
import com.scm.common.utils.DateUtils;
import com.scm.common.utils.StringUtils;
import com.scm.common.utils.poi.ExcelUtil;
import com.scm.dto.req.inventory.SaveScmInventoryOutReq;
import com.scm.dto.resp.invent.QueryInventoryOutPageResp;
import com.scm.dto.resp.invent.ScmInventoryOutDetailDo;
import com.scm.manager.OrderManager;
import com.scm.persist.model.ScmInventoryOut;
import com.scm.persist.model.ScmInventoryOutDetail;
import com.scm.service.IScmInventoryOutService;
import com.scm.web.controller.inventory.vo.ScmInventoryOutProductDetailsVO;
import com.scm.web.controller.inventory.vo.ScmInventoryOutVO;
import org.apache.commons.compress.utils.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 库存-出库信息Controller
 * 
 * @author reptilemanager
 * @date 2024-03-17
 */
@Controller
@RequestMapping("/scm/inventory/out")
public class ScmInventoryOutController extends BaseController
{
    private String prefix = "inventory/out";


    @Autowired
    private OrderManager orderManager;

    @Autowired
    private IScmInventoryOutService scmInventoryOutService;

    @RequiresPermissions("system:in:view")
    @GetMapping()
    public String in()
    {
        return prefix + "/out";
    }

    /**
     * 查询库存-出库信息列表
     */
    @RequiresPermissions("system:in:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ScmInventoryOut scmInventoryOut)
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer start = (pageDomain.getPageNum() - 1) * 10;
        QueryInventoryOutPageResp resp = scmInventoryOutService.selectScmInventoryOutList(scmInventoryOut,start,pageDomain.getPageSize());
        return getDataTable(resp.getList());
    }

    /**
     * 导出库存-出库信息列表
     */
    @RequiresPermissions("system:in:export")
    @Log(title = "库存-出库信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ScmInventoryOut scmInventoryOut)
    {
        QueryInventoryOutPageResp resp  = scmInventoryOutService.selectScmInventoryOutList(scmInventoryOut,0,10);
        ExcelUtil<ScmInventoryOut> util = new ExcelUtil<ScmInventoryOut>(ScmInventoryOut.class);
        return util.exportExcel(resp.getList(), "库存-出库信息数据");
    }

    /**
     * 新增库存-出库信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }


    @GetMapping("/orderToAdd/{orderId}")
    public String orderToAdd(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        SysUser sysUser = getSysUser();

        ScmInventoryOut inventoryOut = orderManager.orderToOutInventory(orderId,sysUser);
        mmap.put("scmInventoryOut", inventoryOut);

        return prefix + "/orderToAdd";
    }
    /**
     * 修改库存-出库信息
     */
    @RequiresPermissions("system:in:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ScmInventoryOut scmInventoryOut = scmInventoryOutService.selectScmInventoryOutById(id);

        if("beInStorage".equals(scmInventoryOut.getStatus())){
            throw new ServiceException("已出库单据不能修改！");
        }

        mmap.put("scmInventoryOut", scmInventoryOut);
        return prefix + "/edit";
    }


    /**
     * 新增保存库存-出库信息
     */
    @RequiresPermissions("system:in:add")
    @Log(title = "库存-出库信息", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    @ResponseBody
    public AjaxResult addOrUpdateSave( ScmInventoryOutVO scmInventoryOutVO)
    {
        SysUser sysUser = getSysUser();

        if(scmInventoryOutVO==null){
            return toAjax(false);
        }

        try {
        if(scmInventoryOutVO.getId()!=null&&scmInventoryOutVO.getId()>0){
            scmInventoryOutService.updateScmInventoryOut(getSaveScmInventoryOutReq(scmInventoryOutVO),sysUser);
        }else{
            scmInventoryOutService.saveScmInventoryOut(getSaveScmInventoryOutReq(scmInventoryOutVO),sysUser);
        }
        } catch (Exception e) {
            return AjaxResult.error(""+e.getMessage());
        }


        return toAjax(1);
    }


    private SaveScmInventoryOutReq getSaveScmInventoryOutReq(ScmInventoryOutVO scmInventoryOutVO){

        SaveScmInventoryOutReq req = new SaveScmInventoryOutReq();

        ScmInventoryOut scmInventoryOut = new ScmInventoryOut();

        scmInventoryOut.setOrderId(scmInventoryOutVO.getOrderId());
        scmInventoryOut.setId(scmInventoryOutVO.getId());
        scmInventoryOut.setCode(scmInventoryOutVO.getCode());
        scmInventoryOut.setName(scmInventoryOutVO.getName());
        scmInventoryOut.setSalesmanName(scmInventoryOutVO.getSalesmanName());
        scmInventoryOut.setRemark(scmInventoryOutVO.getRemark());

        if(!StringUtils.isEmpty(scmInventoryOutVO.getOutDatetime())){
            scmInventoryOut.setOutDatetimeStr(scmInventoryOutVO.getOutDatetime());
            scmInventoryOut.setOutDatetime(DateUtils.parseDate(scmInventoryOutVO.getOutDatetime()).getTime());
        }


        req.setScmInventoryOut(scmInventoryOut);

        List<ScmInventoryOutDetail> scmInventoryInDetailList = Lists.newArrayList();

        List<ScmInventoryOutProductDetailsVO> details  = scmInventoryOutVO.getProducts();

        for (ScmInventoryOutProductDetailsVO detail : details) {
            ScmInventoryOutDetail inventoryOutDetail = new ScmInventoryOutDetail();
            inventoryOutDetail.setStashProductId(detail.getStashProductId());
            inventoryOutDetail.setRemark(detail.getRemark());
            inventoryOutDetail.setOutStashAmount(detail.getOutStashAmount());
            inventoryOutDetail.setProductCount(detail.getOutCount());

            scmInventoryInDetailList.add(inventoryOutDetail);
        }

        req.setScmInventoryOutDetailList(scmInventoryInDetailList);
        return req;

    }

    /**
     * 修改保存库存-出库信息
     */
    @RequiresPermissions("system:in:edit")
    @Log(title = "库存-出库信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ScmInventoryOut scmInventoryOut)
    {
        return toAjax(scmInventoryOutService.updateScmInventoryOut(scmInventoryOut));
    }

    /**
     * 删除库存-出库信息
     */
    @RequiresPermissions("system:in:remove")
    @Log(title = "库存-出库信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {

        int i =  scmInventoryOutService.deleteScmInventoryOutById(ids);
        return toAjax(i);
    }


    /**
     * 查询库存-出库信息列表
     */
    @PostMapping("/detail/list")
    @ResponseBody
    public TableDataInfo detailList(@RequestParam("id") Long id, ModelMap mmap)
    {
        if(id==null||id==0){
            return getDataTable(Lists.newArrayList());
        }

        List<ScmInventoryOutDetailDo> list = scmInventoryOutService.selectScmInventoryOutDetailListList(id);
        return getDataTable(list);
    }


    /**
     * 查询库存-出库信息列表
     */
    @PostMapping("/detail/listByOrderId")
    @ResponseBody
    public TableDataInfo listByOrderId(@RequestParam("orderId") Long orderId, ModelMap mmap)
    {
        if(orderId==null||orderId==0){
            return getDataTable(Lists.newArrayList());
        }

        SysUser sysUser = getSysUser();

        List<ScmInventoryOutDetailDo> list = orderManager.queryOrderProductToOutInventory(orderId,sysUser);
        return getDataTable(list);
    }


    @PostMapping("/confirmScmInventoryOut/{id}")
    @ResponseBody
    public AjaxResult confirmScmInventoryIn(@PathVariable("id") Long id, ModelMap mmap)
    {
        try {
            if(id==null||id==0){
                return toAjax(false);
            }

            SysUser sysUser = getSysUser();
            scmInventoryOutService.confirmScmInventoryOut(id,sysUser);
            return toAjax(true);
        } catch (Exception e) {
            return AjaxResult.error(""+e.getMessage());
        }


    }


}
